/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * This the class that establishes the connection to the database,
 * which is also getting its user and password from the config file
 */
package db;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Class that creates a connection to the database.
 * @author esc348
 */

public class DBConnector {
    private static Connection conn;
    private static String URL = null;
    private static String forName = null;
    private static String dbUserName = null;
    private static String dbPW = null;
    /**
     * Establishes and returns a connection to the database.
     * @return Connection
     */
    public static Connection connect() 
    {
        try 
        {
            if (URL == null) 
            {
                Properties p = new Properties();
                try 
                {
                    p.load(DBConnector.class.getResourceAsStream("db.properties"));
                    URL = p.getProperty("connectstring");
                    forName = p.getProperty("driver");
                    dbUserName = p.getProperty("username");
                    dbPW = p.getProperty("password");
                } 
                catch (IOException ex) 
                {
                    Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
                }
               
            }

            Class.forName(forName);
            conn = DriverManager.getConnection(URL, dbUserName,dbPW);
            conn.setAutoCommit(false);
        } 
        catch(SQLException ex) 
        {
            System.out.println("DBConFactory:SQLException:"+ex.getMessage());

        }
        catch(ClassNotFoundException ex)
        {
             System.out.println("DBConFactory:ClassNotFoundException:"+ex.getMessage());
        }

        return conn;
    }
}
